<template>
  <px-dialog v-model="visible" class="tool-dialog" title="标注标签" width="800px" @open="openDialog" @close="closeDialog">
    <div class="tool-dialog-content">
      <px-form ref="formRef" class="tool-dialog-form" :model="formValue" :rules="rules" label-position="right" label-width="120px">
        <px-form-item label="标签" prop="measureTags">
          <px-cascader
            v-model="formValue.measureTags"
            filterable
            clearable
            style="width: 100%"
            :options="tagList"
            :props="defaultProps"
            placeholder="请选择标签"
          />
        </px-form-item>
        <px-form-item label="关联指标编码" prop="measures">
          <px-select
            v-model="formValue.measures"
            clearable
            filterable
            multiple
            remote
            :remote-method="tagCodeRemote"
            placeholder="请输入关联指标编码"
            style="width: 100%"
            value-key="measureCode"
          >
            <px-option v-for="item in measureCodeList" :key="item.measureCode" :label="item.measureName" :value="item" />
          </px-select>
        </px-form-item>
        <px-form-item label="">
          <px-input
            v-model="formValue.copyText"
            type="textarea"
            placeholder="可在此复制或输入指标编码进行批量查找(换行分隔)"
            maxlength="2000"
            :autosize="{ minRows: 3, maxRows: 10 }"
            clearable
          />
          <px-button type="primary" style="margin-top: 10px" plain @click="handleSearch">查询</px-button>
        </px-form-item>
      </px-form>
      <div style="margin-top: 16px; text-align: right">
        <px-button @click="closeDialog">取消</px-button>
        <px-button type="primary" @click="handleSubmit(formRef)">确认</px-button>
      </div>
    </div>
  </px-dialog>
</template>
<script setup lang="ts">
import { queryDictData } from "@/api/common";
import { addMeasureTag, searchMeasure, searchMeasureArr } from "@/api/system/measure";
import { PxMessage } from "px-ui";
import { computed, reactive, toRefs } from "vue";

// 调用父级-查询主页列表、关闭弹窗方法
const emits = defineEmits(["queryTable", "closeDialog"]);
// 父级传过来的值
const props = defineProps({
  // 控制弹窗显示隐藏
  visible: {
    type: Boolean,
    default: false
  }
});
const visible = computed(() => props.visible);

const defaultProps = {
  children: "children",
  label: "name",
  value: "value",
  multiple: true
};

const state = reactive<any>({
  formRef: null,
  formValue: {
    measures: [],
    measureTags: []
  },
  measureCodeList: [],
  tagList: [] // 标签
});
const { formRef, formValue, measureCodeList, tagList } = toRefs(state);

const rules = computed(() => ({
  measureTags: [{ required: true, message: "标签不能为空", trigger: "change" }],
  measures: [{ required: true, message: "关联指标编码不能为空", trigger: ["blur", "change"] }]
}));

// 获取标签
const queryTagSelect = async () => {
  tagList.value = await queryDictData({ typeCode: "measure_tag" });
};

const handleSearch = async () => {
  const data = await searchMeasureArr({ measureCodes: formValue.value.copyText.split("\n") || [] });
  if (data && data?.length !== 0) {
    measureCodeList.value = measureCodeList.value?.concat(data)?.filter((obj, index, self) => {
      return self.map(x => x.measureCode).indexOf(obj.measureCode) === index;
    });
    formValue.value.measures = formValue.value.measures?.concat(data)?.filter((obj, index, self) => {
      console.log(self, obj, self.map(x => x.measureCode).indexOf(obj.measureCode) === index);
      return self.map(x => x.measureCode).indexOf(obj.measureCode) === index;
    });
    console.log(formValue.value.measures, measureCodeList.value);
    formValue.value.copyText = [];
  }
};

// 打开弹窗
const openDialog = async () => {
  formRef.value.resetFields();
  formValue.value.measures = [];
  queryTagSelect();
};

// 查询列表关闭弹窗
const closeDialog = () => {
  formValue.value.copyText = [];
  measureCodeList.value = [];
  emits("closeDialog");
};

// 计算否情况-绑定点位过滤,需要节流
const tagCodeRemote = async val => {
  // 绑定点位必须输入内容才能调用接口，否则10w+数据会页面卡死
  if (val) {
    measureCodeList.value = await searchMeasure({ measureCode: val.trim() });
  } else {
    measureCodeList.value = [];
  }
};

// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const params = JSON.parse(JSON.stringify(formValue.value));
      const { measureTags } = params;
      const res = measureTags.map(item => item[item.length - 1]);
      delete params.copyText;
      await addMeasureTag({ ...params, measureTags: res });
      PxMessage.success("标注标签成功！");
      emits("closeDialog");
      emits("queryTable");
    }
  });
};
</script>
